#!/bin/bash
# atv-bootloader Patchstick builder script

# Usage: sudo ../linux_build_patchstick.sh /dev/sdX

#
#	Use with great caution.
#
# 	Use ONLY if you under these conditions:
#	1) You have a USB-stick (minimum 128mb) plugged in but not mounted
# 	2) You are executing it from the directory where your recovery files live
#	3) This script (make_ps.sh) lives one level above 'recovery'
#	4) This script expects you to run it as such: 'sudo ../linux_build_patchstick.sh'
#

# Welcome Screen
clear
echo
echo "   ############################################"
echo "   ##"
echo "   ##    atv-bootloader Patchstick builder"
echo "   ##"
echo "   ##    Created by: h3lbr0 // atvMod.com"
echo "   ##"
echo "   ############################################"
echo
echo

if [ "$USER" != "root" ]
then
	echo "You need to run this script as ROOT. Exiting..."
	echo
	echo
	exit 1
fi

if [ $# -ne 1 ]
then
	echo "Listing available disks:"
	ls /dev/sd?
	echo $'\a'
	echo "Please specify the disk to re-partition as argument one:"
	echo "./make_ps.sh /dev/sdX"
	echo
	echo "WARNING: The disk will be ERASED !!!"
	echo
	echo
	exit 1
fi

partition_disk() {
	echo "    Writing some zeros to $THEDISK..."
	sudo dd if=/dev/zero of=$THEDISK bs=1M &> /dev/null
	sleep 1
	echo "    Making Partitions on $THEDISK..."
	sudo parted -s $THEDISK mklabel gpt
	sleep 1
	sudo parted -s $THEDISK mkpart primary HFS 40s 100M
	sleep 1
	sudo parted -s $THEDISK set 1 atvrecv on
	sleep 1
}

create_filesystem() {
	echo "    Creating File System..."
	sudo mkfs.hfsplus -v Recovery $THEPART > /dev/null
	sleep 1
	sync
}

mount_drive() {
	echo "    Mounting $THEPART..."
	sudo mkdir -p /media/Recovery/
	sudo mount $THEPART /media/Recovery/
	sleep 2
}

copy_files() {
	echo "    Copying Files..."
	sudo cp -arp ./* /media/Recovery/
}

unmount_drive() {
	echo "    Unmounting $THEPART..."
	sudo umount /media/Recovery/
	sleep 2
}

if [ $# = 1 ]
then
	read -p "Are you sure you want to partition disk $1? [yes|no]: " sure
	echo
	THEDISK=$1
	THEPART=$THEDISK"1"
	export THEDISK
	export THEPART

	case "$sure" in
		yes)
			echo
			partition_disk
			create_filesystem
			mount_drive
			copy_files
			unmount_drive
			echo
			echo "  Patchstick is done. Enjoy... :-)"
			echo
			echo
		;;
		*)
			echo "You didn't type yes. Aborting..."
			echo
			echo
			exit
		;;
	esac   
fi


